package org.spindle.soasuite.datasource.internal.core;

import org.spindle.soasuite.core.logging.Log;
import org.spindle.soasuite.core.logging.LogFactory;
import org.spindle.soasuite.datasource.helper.HibernateUtil;
import org.spindle.soasuite.datasource.internal.api.IEndpointDAO;
import org.spindle.soasuite.datasource.internal.api.IUserDAO;

public class InternalDS {

    private static Log log = LogFactory.getLogger(InternalDS.class);

    private Boolean transactionActive = false;

    private IUserDAO userDAO;

    private IEndpointDAO endpointDAO;

    public IUserDAO getUserDAO() {
        prepareTransaction();
        if (userDAO == null) {
            userDAO = new UserDAO();
        }

        return userDAO;
    }

    public IEndpointDAO getEndpointDAO() {
        prepareTransaction();
        if (endpointDAO == null) {
            endpointDAO = new EndpointDAO();
        }

        return endpointDAO;
    }

    public void persist(Object obj) {
        log.logDebug("Preparing to persist: " + obj.getClass().getSimpleName());
        prepareTransaction();
        HibernateUtil.currentSession().persist(obj);
    }

    public void merge(Object obj) {
        prepareTransaction();
        HibernateUtil.currentSession().merge(obj);
    }

    public void refresh(Object obj) {
        prepareTransaction();
        HibernateUtil.currentSession().refresh(obj);
    }

    public void delete(Object obj) {
        prepareTransaction();
        HibernateUtil.currentSession().delete(obj);
    }


    private void prepareTransaction() {
        if (!transactionActive) {
            HibernateUtil.currentSession().beginTransaction();
            transactionActive = true;
        }
    }

    public void commitTransaction() {
        if (transactionActive) {
            HibernateUtil.currentSession().getTransaction().commit();
            HibernateUtil.closeSession();
            transactionActive = false;
        }

    }


}
